package com.bjtang.fileSync.nio;

import java.io.File;
import java.io.IOException;
import java.nio.channels.SocketChannel;

import com.bjtang.fileSync.enums.STATE;
import com.bjtang.fileSync.util.FileCODEC;
import com.bjtang.fileSync.util.FileConfig;
import com.bjtang.fileSync.util.FileMd5;

public class FileService {
	private String path;

	public FileService() {
		path = FileConfig.readConfig("path").trim();
	}

	/*
	 * 上传文件至服务器 //服务器接受 //反向使用就是服务器向客户端发送
	 */
	public void fileDownload(SocketChannel socketChannel, SocketDto socketDto) throws IOException {
		File file = new File(path + socketDto.getFileName());
		// 自动创建file路径
		if (!file.exists()) {
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
		}
		// 写入数据
		if (socketDto.getFileMd5() != null) {
			FileCODEC.channelWriteChanne(socketChannel, file, socketDto.getFileSize());
			String md5ByFile = FileMd5.getMd5ByFile(file);
			// 最后修改时间
			file.setLastModified(socketDto.getFileLastTime());
			if (md5ByFile.equals(socketDto.getFileMd5())) {
				FileCODEC.writeChannel(socketChannel, STATE.SUCCESS.name());
			} else {
				FileCODEC.writeChannel(socketChannel, STATE.FILE_BAD.name());
			}
		} else {
			FileCODEC.writeChannel(socketChannel, STATE.COMMUNICATION_UNSAFE.name());
		}
	}

	/*
	 * 下载文件至服务器 //服务器发送
	 */
	public void fileUpload(SocketChannel socketChannel, SocketDto socketDto) throws IOException {
		File file = new File(path + socketDto.getFileName());
		if (!file.exists()) {
			FileCODEC.writeChannel(socketChannel, STATE.FILE_NOT_FOUND.name());
			return;
		}
		// 写入数据
		FileCODEC.channelReadChanne(socketChannel, file);
		System.err.println("fileUpload " + new String(FileCODEC.readChannel(socketChannel)));
	}

	/*
	 * 删除文件
	 */
	public void fileRemove(SocketChannel socketChannel, SocketDto socketDto) throws IOException {
		File file = new File(path+socketDto.getFileName());
		if (file.exists()) {
			if (file.delete()) {
				FileCODEC.writeChannel(socketChannel, STATE.SUCCESS.name());
			} else {
				FileCODEC.writeChannel(socketChannel, STATE.FAILURE.name());
			}
		} else {
			FileCODEC.writeChannel(socketChannel, STATE.SUCCESS.name());
		}
	}

	/*
	 * 比对文件
	 */
	public void fileCheck(SocketChannel socketChannel, SocketDto socketDto) throws IOException {
		// TODO
	}

	/*
	 * 比对所有文件
	 */
	public void fileCheckAll(SocketChannel socketChannel, SocketDto socketDto) throws IOException {
		// TODO
	}
}
